package server.layer;

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;

/**
 * Created by IntelliJ IDEA.
 * User: Awake
 * Date: 22.04.12
 * Time: 18:41
 * To change this template use File | Settings | File Templates.
 */
public class ServiceServer implements Runnable {

    private static final int PORT = 8189;
    private Socket client;
    private ServerSocket server;
    ArrayList<Thread> threads = new ArrayList<Thread>();
    Thread servThread;

    public ServiceServer() {
        try {
            server = new ServerSocket(PORT);
            servThread = new Thread(this);
            servThread.start();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void run() {
        while (true) {
            try {
                client = server.accept();
                System.out.println("connection ID : " + client.hashCode());
                Thread t = new Thread(new ServerThread(client, this));
                t.start();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public void sendMessageTo(Socket s, String mess) {
        try {
            PrintWriter out = new PrintWriter(
                    new BufferedWriter(new OutputStreamWriter(s.getOutputStream())), true);
            out.println(mess);
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println("[to " + s.hashCode() + "] : " + mess);
    }

    public void kill() throws IOException {
        for (Thread t : threads) {
            t.stop();
        }
        servThread.stop();
    }
}
